import { createReducer, on } from '@ngrx/store'
import { addTodo, delTodo } from '../actions/counter.actions'
import { v4 as uuidv4 } from 'uuid';
export const counterFeatureKey = 'counter'

export interface Todo {
  id: string
  title: string
}

export interface State {
  todos: Todo[]
}

export const initialState: State = {
  todos: [],
}

export const reducer = createReducer(
  initialState,
  on(addTodo, (state, action) => ({
    ...state,
    todos: [
      ...state.todos,
      {
        id:  uuidv4(),
        title: action.title,
      },
    ],
  })),
  on(delTodo, (state, action) => {
    const newState:State = JSON.parse(JSON.stringify(state) )
    const index =  newState.todos.findIndex(({id}) => id === action.id)
    newState.todos.splice(index,1)
    return newState
  })
)
